﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace CssAndJsCombiner
{
    public class ClientResourcePathLoader : IClientResourceLoader
    {
        private bool _sucess = false;

        public bool TryLoad(ClientResourceType type, string path, string[] vars, out string body)
        {
            StringBuilder sbPath = new StringBuilder(path);

            for (int i = 0; i < vars.Length; i++)
            {
                sbPath.Replace(String.Format("$(var{0})", (i + 1)), vars[i]);
            }

            path = sbPath.ToString();

            body = LoadPath(type, path);
            return _sucess;
        }

        private string LoadPath(ClientResourceType type, string path)
        {
            string content = String.Empty;
            if (path.StartsWith("http"))
            {
                try
                {
                    Uri url = new Uri(path, UriKind.Absolute);

                    using (WebClient client = new WebClient())
                    {
                        using (Stream buffer = client.OpenRead(url))
                        {
                            using (StreamReader reader = new StreamReader(buffer))
                            {
                                content = reader.ReadToEnd();
                            }
                        }
                    }
                }
                catch (WebException)
                {
                    // Unable to connect
                    _sucess = false;
                }
            }
            else
            {
                path = WebContext.MapPath(path);

                if (type == ClientResourceType.Js && !WebContext.IsDebugMode)
                {
                    string minPath = path.Replace(".js", ".min.js");
                    if (File.Exists(minPath)) path = minPath;
                }

                content = File.ReadAllText(path);
            }

            _sucess = true;
            return content;
        } 
    }
}
